package util

import (
	"backEnd/model"
	"fmt"
	"math/rand"
	"strings"

	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
)

var CHARS = []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
	"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
	"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}

// 生成随机字符串
func RandAllString(lenNum int) string {
	str := strings.Builder{}
	length := len(CHARS)
	for i := 0; i < lenNum; i++ {
		l := CHARS[rand.Intn(length)]
		str.WriteString(l)
	}
	return str.String()
}

// 生成随机数字串
func RandNumString(lenNum int) string {
	str := strings.Builder{}
	length := 10
	for i := 0; i < lenNum; i++ {
		str.WriteString(CHARS[52+rand.Intn(length)])
	}
	return str.String()
}

// 生成随机纯字符串
func RandString(lenNum int) string {
	str := strings.Builder{}
	length := 52
	for i := 0; i < lenNum; i++ {
		str.WriteString(CHARS[rand.Intn(length)])
	}
	return str.String()
}

func GetUpdatedValue(originalValue string, updatedValue string) string {
	if updatedValue != "" {
		return updatedValue
	}
	return originalValue
}

func IsTelephoneExists(db *gorm.DB, telephone string) bool {
	var user model.User
	db.Where("telephone = ?", telephone).First(&user)
	return user.ID != 0
}

// 生成图片url
func GenerateImgUrl(filename string) string {
	bucketname := viper.GetString("cos.bucketname")
	appId := viper.GetString("cos.appId")
	region := viper.GetString("cos.region")
	cosUrl := fmt.Sprintf("https://%s-%s.cos.%s.myqcloud.com", bucketname, appId, region)
	imgUrl := fmt.Sprintf("%s/%s", cosUrl, filename)
	if strings.HasPrefix(filename, cosUrl) {
		return filename
	}
	return imgUrl
}
